package org.springframework.ai.mcp.server.demo.tools;

import com.fasterxml.jackson.databind.ObjectMapper;
import io.modelcontextprotocol.server.McpServerFeatures;
import io.modelcontextprotocol.spec.McpSchema;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.List;

/**
 * 文本处理工具配置类，提供各种文本操作功能。
 */
@Configuration
public class TextToolsConfiguration {

    private static final Logger logger = LoggerFactory.getLogger(TextToolsConfiguration.class);
    private final ObjectMapper objectMapper = new ObjectMapper();

    /**
     * 文本工具集合：包含所有文本处理相关的工具。
     */
	@Bean
	public List<McpServerFeatures.SyncToolSpecification> textTools() {
		return List.of(createAnalyzeTextTool(), createReverseTool());
	}

	/**
     * 文本分析工具：统计文本的各种信息。
     */
	private McpServerFeatures.SyncToolSpecification createAnalyzeTextTool() {
		String schemaJson = """
        {
          "type": "object",
          "properties": {
            "text": { "type": "string", "description": "要分析的文本" }
          },
          "required": ["text"]
        }
        """;

		McpSchema.Tool tool = new McpSchema.Tool("analyze_text", "分析文本，返回字符数、单词数等统计信息", schemaJson);

		return new McpServerFeatures.SyncToolSpecification(
				tool,
				(exchange, arguments) -> {
					try {
						// 直接从Map中获取参数值
						Object textValue = arguments.get("text");
						String text = textValue != null ? textValue.toString() : "";

						int charCount = text.length();
						int wordCount = text.trim().isEmpty() ? 0 : text.trim().split("\\s+").length;
						int lineCount = text.split("\n").length;

						String result = String.format("""
                    文本分析结果:
                    - 字符数: %d
                    - 单词数: %d
                    - 行数: %d
                    - 是否为空: %s
                    """, charCount, wordCount, lineCount, text.trim().isEmpty() ? "是" : "否");

						logger.info("执行文本分析: 字符数={}, 单词数={}, 行数={}", charCount, wordCount, lineCount);

						return new McpSchema.CallToolResult(new McpSchema.TextContent(result).text(), false);
					} catch (Exception e) {
						logger.error("文本分析失败", e);
						return new McpSchema.CallToolResult(new McpSchema.TextContent("错误：" + e.getMessage()).text(), true);
					}
				}
		);
	}


	/**
     * 文本反转工具。
     */
	private McpServerFeatures.SyncToolSpecification createReverseTool() {
		String schemaJson = """
        {
          "type": "object",
          "properties": {
            "text": { "type": "string", "description": "要反转的文本" }
          },
          "required": ["text"]
        }
        """;

		McpSchema.Tool tool = new McpSchema.Tool("reverse", "反转文本字符顺序", schemaJson);

		return new McpServerFeatures.SyncToolSpecification(
				tool,
				(exchange, arguments) -> {
					try {
						// 直接从Map中获取参数值
						Object textValue = arguments.get("text");
						String text = textValue != null ? textValue.toString() : "";
						String result = new StringBuilder(text).reverse().toString();

						logger.info("执行文本反转: {} -> {}", text, result);

						return new McpSchema.CallToolResult(new McpSchema.TextContent(result).text(), false);
					} catch (Exception e) {
						logger.error("文本反转失败", e);
						return new McpSchema.CallToolResult(new McpSchema.TextContent("错误：" + e.getMessage()).text(), true);
					}
				}
		);
	}


}
